package com.home.demo.security;


import com.alibaba.fastjson.JSONObject;
import com.home.demo.common.JwtUtil;
import com.home.demo.common.RedisCache;
import com.home.demo.common.ResponseCode;
import com.home.demo.entity.vo.user.UserLoginVO;
import com.home.demo.fitler.UserOperationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserOperationInterceptor userOperationInterceptor;

    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPoint;



    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }



    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/user/login", "/user/save","/websocket/*","/**").permitAll()
//                .anyRequest().authenticated()
                .and().formLogin().loginPage("/user/login").successHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                SecurityUserDetailsImpl principal = (SecurityUserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                Map<String,Object> loginDetailsMap = new HashMap<>();
                response.setContentType("application/json;charset=UTF-8");
                loginDetailsMap.put("code",0);

                UserLoginVO userEntity = principal.getUserLoginVO();
                String jwt = JwtUtil.createJWT(userEntity.getId());
                redisCache.setCacheObject(userEntity.getId(),userEntity);
                loginDetailsMap.put("token",jwt);
                loginDetailsMap.put("data",userEntity);
                String s = JSONObject.toJSONString(loginDetailsMap);
                response.getWriter().print(s);

            }
        }).failureHandler(new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                Map<String,Object> map = new HashMap();
                map.put("code", ResponseCode.ERR.getCode());
                map.put("msg","您输入的账号或密码有误");
                String s = JSONObject.toJSONString(map);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print(s);
            }
        })
                .and().logout().logoutUrl("/user/logout").logoutSuccessHandler(new LogoutSuccessHandler() {
            @Override
            public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                String token = request.getHeader("token");
                Map<String,Object> logoutDetailsMap = new HashMap<>();
                if (!StringUtils.hasText(token)) {
                    logoutDetailsMap.put("code",403);
                    logoutDetailsMap.put("msg","token获取失败");
                    String s = JSONObject.toJSONString(logoutDetailsMap);
                    response.getWriter().print(s);
                }
                try {
                    String id  = JwtUtil.parseJWT(token).getSubject();
                    redisCache.deleteObject(id);
                    logoutDetailsMap.put("code",0);
                    logoutDetailsMap.put("msg","退出成功");
                    String s = JSONObject.toJSONString(logoutDetailsMap);
                    response.getWriter().print(s);
                    return;
                } catch (Exception e) {
                    return;
                }

            }
        })
                .and().cors().and().addFilterBefore(userOperationInterceptor, UsernamePasswordAuthenticationFilter.class)
        .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);

    }



}
